<template>
  <section>
    <el-card>
      <el-page-header @back="$router.back()" content="压缩图片" />
    </el-card>

    <el-card class="mt-20" header="请选择图片">
      <input type="file" name="" id="" @change="handleChange" />
      <p v-if="input.size">原图大小 {{input.size / 1024}} Kb</p>
    </el-card>

    <el-card class="mt-20" header="压缩结果">
      <el-progress :percentage="imageCompressionProgress"></el-progress>
      <el-image :src="file" alt="" />
      <p v-show="output.name">名称 {{ output.name }}</p>
      <p v-show="output.type">类型 {{ output.type }}</p>
      <p v-if="output.size">大小 {{ output.size / 1024 }} Kb</p>
    </el-card>
  </section>
</template>

<script>
import imageCompression from "browser-image-compression";
export default {
  data() {
    return {
      file: "",
      imageCompressionProgress: 0,
      output: {},
      input: {},
    };
  },
  methods: {
    async handleChange(v) {
      const output = await imageCompression(v.target.files[0], {
        maxSizeMB: 1,
        maxWidthOrHeight: 960,
        useWebWorker: true,
        onProgress: this.onProgress,
      });
      this.input = v.target.files[0];
      const reader = new FileReader();
      reader.onload = (a) => {
        this.file = a.target.result;
      };
      reader.readAsDataURL(output);
      window.console.log(output);
      this.output = output;
    },

    onProgress(v) {
      this.imageCompressionProgress = v;
    },
  },
};
</script>

<style></style>
